//
//  HomeViewController.m
//  LEVE
//
//  Created by 王若聪 on 2016/12/6.
//  Copyright © 2016年 dashuju. All rights reserved.
//

#import "LVCameraViewController.h"
#import "ViewUtils.h"
#import "LVImageViewController.h"
#import "LVVideoViewController.h"
#import "HYRecordingButton.h"
#import "LVThreeBtnTool.h"

@interface LVCameraViewController ()<HYRecordingButtonDelegate>
@property (strong, nonatomic) LLSimpleCamera *camera;
@property (strong, nonatomic) UIButton *switchButton;
@property (strong, nonatomic) UIButton *flashButton;
@property (strong, nonatomic) UIButton *ghostButton;

@property (assign, nonatomic) CGFloat lastLongpressGesturePointY;
@property (assign, nonatomic) CGFloat lastCameraScale;
@property (strong, nonatomic) HYRecordingButton *recordingButton;
@end

@implementation LVCameraViewController

- (void)viewDidLoad{
    [super viewDidLoad];
    
    //测试
    LVThreeBtnTool *tool = [LVThreeBtnTool shareThreeBtn];
    [tool hideMiddleBtn:YES];
    
    self.view.backgroundColor = [UIColor blackColor];
    
    
    [self initializeCamera];
    
    [self setupCameraButtons];
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    // start the camera
    [self.camera start];
}
#pragma mark recordingButton
- (HYRecordingButton *)recordingButton{
    if (!_recordingButton) {
        CGFloat width = self.view.frame.size.width;
        CGFloat heigth = self.view.frame.size.height;
        CGFloat itemWidth = 70;
        HYRecordingButton *recordCircleView = [[HYRecordingButton alloc] initWithFrame:CGRectMake((width - itemWidth)/2,heigth - itemWidth - 15, itemWidth, itemWidth)];
        
        recordCircleView.tintColor = [UIColor whiteColor];
        recordCircleView.filledLineStyleOuter = NO;
        recordCircleView.isClickedAmpl = YES;
        recordCircleView.delegate = self;
        [self.view addSubview:recordCircleView];
        _recordingButton = recordCircleView;
    }
    return _recordingButton;
}
#pragma mark HYRecordingButtonDelegate
//录像
- (void)startRecordingAtRecordingButton:(HYRecordingButton *)recordingButton withProgress:(double)progress andPoint:(CGPoint)point{
    if(!self.camera.isRecording) {
        self.flashButton.hidden = YES;
        self.switchButton.hidden = YES;
        
        // start recording
        NSURL *outputURL = [[[self applicationDocumentsDirectory]
                             URLByAppendingPathComponent:@"test1"] URLByAppendingPathExtension:@"mov"];
        
        __weak typeof(self) weakSelf = self;
        [self.camera startRecordingWithOutputUrl:outputURL didRecord:^(LLSimpleCamera *camera, NSURL *outputFileUrl, NSError *error) {
            LVVideoViewController *vc = [[LVVideoViewController alloc] initWithVideoUrl:outputFileUrl];
            
            [weakSelf presentViewController:vc animated:NO completion:nil];
        }];
        
        
        self.lastLongpressGesturePointY = point.y;
        self.lastCameraScale = 1.0f;
    }
}
- (void)finishedRecordingAtRecordingButton:(HYRecordingButton *)recordingButton withProgress:(double)progress andPoint:(CGPoint)point{
    self.flashButton.hidden = NO;
    self.switchButton.hidden = NO;
    
    [self.camera stopRecording];
}

- (void)chagedRecordingAtRecordingButton:(HYRecordingButton *)recordingButton withProgress:(double)progress andPoint:(CGPoint)point{
    long double y =  point.y - self.lastLongpressGesturePointY;
    if (y < 0.f) {
        //swip up
        self.lastCameraScale += 0.05f;
    }else{
        //swip down
        self.lastCameraScale -= 0.05f;
    }
    
    if (self.lastCameraScale < 1.0f){
        self.lastCameraScale = 1.0f;
    }
    
    NSError *error = nil;
    if ([self.camera.videoCaptureDevice lockForConfiguration:&error]) {
        [self.camera.videoCaptureDevice rampToVideoZoomFactor:self.lastCameraScale withRate:100];
        [self.camera.videoCaptureDevice unlockForConfiguration];
    }
    self.lastLongpressGesturePointY = point.y;
}
//拍照
- (void)takingAtRecordingButton:(HYRecordingButton *)recordingButton{
    __weak typeof(self) weakSelf = self;
    
    //测试
    //    LVImageViewController *imageVC = [[LVImageViewController alloc] initWithImage:[UIImage imageNamed:@"sample"]];
    //    [self presentViewController:imageVC animated:NO completion:nil];
    
    // capture image
    [self.camera capture:^(LLSimpleCamera *camera, UIImage *image, NSDictionary *metadata, NSError *error) {
        if(!error) {
            LVImageViewController *imageVC = [[LVImageViewController alloc] initWithImage:image];
            [weakSelf presentViewController:imageVC animated:NO completion:nil];
        }
        else {
            NSLog(@"An error has occured: %@", error);
        }
    } exactSeenImage:YES];
}

#pragma mark - camera Buttons methods

- (void)switchButtonPressed:(UIButton *)button{
    [self.camera togglePosition];
}

- (void)flashButtonPressed:(UIButton *)button{
    if(self.camera.flash == LLCameraFlashOff) {
        BOOL done = [self.camera updateFlashMode:LLCameraFlashOn];
        if(done) {
            self.flashButton.selected = YES;
            self.flashButton.tintColor = [UIColor yellowColor];
        }
    }
    else {
        BOOL done = [self.camera updateFlashMode:LLCameraFlashOff];
        if(done) {
            self.flashButton.selected = NO;
            self.flashButton.tintColor = [UIColor whiteColor];
        }
    }
}

- (void)ghostButtonPressed:(UIButton *)button{
    //切换回乐无世界
    
}

#pragma mark - other lifecycle methods
- (void)setupCameraButtons{
    // ----- camera buttons -------- //
    self.recordingButton.hidden = NO;
    
    // button to toggle flash
    self.flashButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.flashButton.frame = CGRectMake(0, 0, 44.0f, 44.0f);
    self.flashButton.tintColor = [UIColor whiteColor];
    [self.flashButton setImage:[UIImage imageNamed:@"camera_flash_press"] forState:UIControlStateNormal];
    //    self.flashButton.imageEdgeInsets = UIEdgeInsetsMake(10.0f, 10.0f, 10.0f, 10.0f);
    [self.flashButton addTarget:self action:@selector(flashButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.flashButton];
    
    //测试
    //    if([LLSimpleCamera isFrontCameraAvailable] && [LLSimpleCamera isRearCameraAvailable]) {
    // button to toggle camera positions
    self.switchButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.switchButton.frame = CGRectMake(0, 0, 44.0f, 44.0f);
    self.switchButton.tintColor = [UIColor whiteColor];
    [self.switchButton setImage:[UIImage imageNamed:@"camera_around"] forState:UIControlStateNormal];
    [self.switchButton addTarget:self action:@selector(switchButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.switchButton];
    //    }
    
    
    // button to toggle flash
    self.ghostButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.ghostButton.frame = CGRectMake(0, 0, 36.0f, 36.0f);
    [self.ghostButton setBackgroundImage:[UIImage imageNamed:@"greet_ghost"] forState:UIControlStateNormal];
    [self.ghostButton addTarget:self action:@selector(ghostButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.ghostButton];
    
}
- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    // use this method to avoid if someday landscripe model is supported
    self.camera.view.frame = self.view.contentBounds;
    
    //    self.snapButton.center = self.view.contentCenter;
    //    self.snapButton.bottom = self.view.height - 15.0f;
    
    self.switchButton.left = 12.0f;
    self.switchButton.top =10.f;
    
    self.flashButton.left = self.switchButton.right + 2.f;
    self.flashButton.top = self.switchButton.top;
    
    self.ghostButton.right = self.view.right - 15.f;
    self.ghostButton.centerY = self.switchButton.centerY;
}

#pragma mark - initial Methods
- (void)initializeCamera{
    // ----- initialize camera -------- //
    
    // create camera vc
    self.camera = [[LLSimpleCamera alloc] initWithQuality:AVCaptureSessionPresetHigh
                                                 position:LLCameraPositionRear
                                             videoEnabled:YES];
    
    // attach to a view controller
    [self.camera attachToViewController:self withFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    
    // read: http://stackoverflow.com/questions/5427656/ios-uiimagepickercontroller-result-image-orientation-after-upload
    // you probably will want to set this to YES, if you are going view the image outside iOS.
    self.camera.fixOrientationAfterCapture = NO;
    
    // take the required actions on a device change
    __weak typeof(self) weakSelf = self;
    [self.camera setOnDeviceChange:^(LLSimpleCamera *camera, AVCaptureDevice * device) {
        
        // device changed, check if flash is available
        if([camera isFlashAvailable]) {
            weakSelf.flashButton.hidden = NO;
            
            if(camera.flash == LLCameraFlashOff) {
                weakSelf.flashButton.selected = NO;
            }
            else {
                weakSelf.flashButton.selected = YES;
            }
        }
        else {
            //测试
            //            weakSelf.flashButton.hidden = YES;
        }
    }];
    
}

- (NSURL *)applicationDocumentsDirectory{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
- (BOOL)prefersStatusBarHidden{
    return YES;
}
- (UIInterfaceOrientation) preferredInterfaceOrientationForPresentation{
    return UIInterfaceOrientationPortrait;
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}

@end
